﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Configuration;

namespace passitumi
{
	/**
	 * This class is where the Main method resides and results in starting
	 * up the GUI as well check for the downloading path if not set.
	 */
	public class MainApplication
	{
		[System.Runtime.InteropServices.DllImport("kernel32.dll")]
		private static extern bool AllocConsole();

		public static PreferenceManager preferences = new WindowsPreferenceManager();

		/**
		 * The main method which will enable the GUI component as well
		 * as checking for the download path setting.
		 */
		[STAThread]
		public static void Main()
		{
			// Comment out the following line to hide the console
			AllocConsole();
			
			Console.WriteLine("MainApplication: Thread Started [{0}]", System.Threading.Thread.CurrentThread.ManagedThreadId);

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			CheckForFirstRun();
			VerifyUserSettings();

			Application.Run(new Gui());
			
			Console.WriteLine("MainApplication: Thread Exited [{0}]", System.Threading.Thread.CurrentThread.ManagedThreadId);
		}

		/**
		 * A method to see of the application has been ran before, if not 
		 * then the user will be prompted to modify basic settings.
		 */
		static void CheckForFirstRun()
		{
			if (preferences.isFirstRun())
			{
				Console.WriteLine("MainApplication: First run detected [{0}]", System.Threading.Thread.CurrentThread.ManagedThreadId);

				PreferencesGui prefs = new PreferencesGui();
				prefs.ShowDialog();
			}
		}

		/**
		 * Check that the two persistent application properties have values when.
		 * If the display name is empty, set the default to the current logged in user's user name.
		 * If the download file path is empty, prompt the user to enter a filepath.
		 */
		static void VerifyUserSettings()
		{
			if (preferences.getDisplayName().Trim().Length == 0)
				preferences.setDefaultDisplayName();

			if (preferences.getDownloadFilePath().Trim().Length == 0)
			{
				PreferencesGui prefs = new PreferencesGui();
				prefs.ShowDialog();
			}
		}
	}
}